import { globalShortcut, ipcMain } from 'electron'
import { IApp } from '../../types'
import openSystemSetting from '../systemSetting'
import { shotKeys } from './data'
import { collectionOfWindows } from '../common/newWindow'

export default (row: IApp) => {
  /**
   * 关闭程序
   */
  ipcMain.on('exit', () => {
    // 程序退出
    row.app.quit()
    // 退出程序进程
    row.app.exit()
  })
  /**
   * 移动窗口
   */
  ipcMain.on('window-move', (_event, config) => {
    row.mainWindow.setBounds(config)
  })
  /**
   * 打开设置
   */
  ipcMain.on('setting', async () => {
    const mainWindow = (await openSystemSetting()).mainWindow
    if (!mainWindow.isVisible()) {
      mainWindow.show()
    }
  })

  /**
   * 打开主程序
   */
  ipcMain.on('main-program', (_event: Electron.Event, status: boolean) => {
    if (!row.mainWindow.isVisible() && status) {
      row.mainWindow.show()
    } else {
      row.mainWindow.hide()
    }
  })
  /**
   * 主程序的显示状态
   */
  ipcMain.handle('get-main-program-visible', () => collectionOfWindows['#/']?.isVisible())

  /**
   * 开启开发工具
   */
  ipcMain.on('open-dev-mode', (_event: Electron.IpcMainEvent, config) => {
    const { modeStatus, shotKeys: shotKey } = JSON.parse(config)
    if (modeStatus) {
      globalShortcut.unregisterAll()
      shotKey.forEach((item: { keywords: string; key: string; enable: boolean }) => {
        const keysFunc =
          shotKeys.find((s) => s.keywords === item.keywords) ||
          ({} as { keywords: string; func: () => void })
        if (item.key && item.enable) {
          globalShortcut.register(item.key, keysFunc.func)
        }
      })
    } else {
      globalShortcut.unregisterAll()
    }
  })
}
